package com.mylg.craw.house.government;

import com.mylg.craw.house.government.category.Article;
import com.mylg.craw.house.government.category.ArticleData;
import com.mylg.craw.house.government.util.Base64ToImage;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * {
 * "id": 176375,
 * "path": "D12Y",
 * "count": 90,
 * "name": "统计信息"
 * },
 */
@Service("governmentCrawDetailService")
public class CrawDetailService {
    @Resource
    private RestClient restClient;

    private static final String DOMAIN = "https://public.zhengzhou.gov.cn";

    public void oneDetail(String url) {
        parseDetailHtml(curlString(url));
    }

    private String curlString(String url) {
        return restClient.get().uri(url).accept(MediaType.ALL).retrieve().body(String.class);
    }

    public ArticleData oneDetail(Article article) {
        if (article == null) {
            return null;
        }
        String data = curlString(article.getUrl());
        return parseDetailHtml(data);
    }


    private ArticleData parseDetailHtml(String body) {
        Document document = Jsoup.parse(body);
        String title = document.getElementsByClass("content-title").get(0).text();
        ArticleData articleData = new ArticleData();
        Elements elements = document.getElementsByAttributeValue("aria-label", "信息正文区");
        if (!elements.isEmpty()) {
            Element bodyElement = elements.first();
            articleData = parseText(bodyElement);
            articleData.setHasImages(parseImage(bodyElement, title));
        }
        //  articleData.setHasImages(parseImage(document, title));

        String month = title.substring(0, title.indexOf("月份") + 1);
        if (StringUtils.hasLength(month)) {
            articleData.setMonth(month);
        }
        return articleData;
    }

    private ArticleData parseText(Element body) {
        String text = body.text();
        return ArticleData.parseFrom(text);
    }

    @SneakyThrows
    public boolean curlImage(String path, String title) {
        String url = path;
        if (path.startsWith("/")) {
            url = DOMAIN.concat(url);
        }

      /*  String response = curlString(url);
        if (response != null) {
            String s = curlString(url);
            FileOutputStream fileOutputStream = new FileOutputStream(title);
            fileOutputStream.write(s.getBytes());
            fileOutputStream.close();
        }*/
        return httpGetImg(url, title);
    }

    public static boolean httpGetImg(String imgUrl, String savePath) {
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(imgUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5, TimeUnit.SECONDS)
                .build();

        //设置请求头
        //  request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");

        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            if (HttpStatus.SC_OK == response.getCode()) {
                HttpEntity entity = response.getEntity();

                InputStream in = entity.getContent();
                FileUtils.copyInputStreamToFile(in, new File(savePath));
                System.out.println("下载图片成功:" + imgUrl);
                return true;
            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return false;
    }


    private boolean parseImage(Element body, String title) {
        Elements img = body.getElementsByTag("img");
        Iterator<Element> iterator = img.iterator();
        int a = 1;

        while (iterator.hasNext()) {
            Element element = iterator.next();
            String src = element.attr("src");
            if (src.startsWith("data:image/png;base64")) {
                Base64ToImage.output(src, String.format("output/%s_%d.png", title, a));
                a++;
            } else if (src.endsWith(".png")) {
                if (curlImage(src, String.format("output/%s_%d.png", title, a))) {
                    a++;
                }


            }
        }
        return a > 1;
    }
}
